class_name SelectionPanel
extends Panel

signal on_selection_completed

@export var players: Array[UnitStats]
@export var start_weapons: Array[ItemWeapon]

@onready var player_icon: TextureRect = %PlayerIcon
@onready var player_name: Label = %PlayerName
@onready var player_title: Label = %PlayerTitle
@onready var player_description: RichTextLabel = %PlayerDescription
@onready var weapon_icon: TextureRect = %WeaponIcon
@onready var weapon_label: Label = %WeaponLabel

@onready var player_container: HBoxContainer = %PlayerContainer
@onready var weapon_container: HBoxContainer = %WeaponContainer

func _ready() -> void:
	show_player_info(false)
	load_players()
	load_weapons()

func load_players() -> void:
	if players.is_empty():
		return
	var player_card: SelectionCard = null
	for i in players.size():
		var player := players[i]
		var current_player_count := player_container.get_child_count()
		if i >= current_player_count:
			player_card = Global.SELECTION_CARD_SCENE.instantiate()
			player_container.add_child(player_card)
		else:
			player_card = player_container.get_child(i)
			if player_card.pressed.is_connected(_on_player_card_pressed):
				player_card.pressed.disconnect(_on_player_card_pressed)
		player_card.pressed.connect(_on_player_card_pressed.bind(player))
		player_card.icon = player.icon
		
func load_weapons() -> void:
	if start_weapons.is_empty():
		return
	var weapon_card: SelectionCard = null
	for i in start_weapons.size():
		var weapon := start_weapons[i]
		var current_weapon_count := weapon_container.get_child_count()
		if i >= current_weapon_count:
			weapon_card = Global.SELECTION_CARD_SCENE.instantiate()
			weapon_container.add_child(weapon_card)
		else:
			weapon_card = weapon_container.get_child(i)
			if weapon_card.pressed.is_connected(_on_weapon_card_pressed):
				weapon_card.pressed.disconnect(_on_weapon_card_pressed)
		weapon_card.pressed.connect(_on_weapon_card_pressed.bind(weapon))
		weapon_card.icon = weapon.item_icon
		
func show_player_info(value: bool) -> void:
	player_icon.visible = value
	player_name.visible = value
	player_title.visible = value
	player_description.visible = value
	weapon_label.visible = value
	
		
func _on_player_card_pressed(player: UnitStats) -> void:
	SoundManager.player_sound(SoundManager.Sound.UI)
	Global.main_selected_player = player
	player_icon.texture = player.icon
	player_name.text = player.name
	player_description.text = player.get_description()
	show_player_info(true)
	
func _on_weapon_card_pressed(weapon: ItemWeapon) -> void:
	SoundManager.player_sound(SoundManager.Sound.UI)
	Global.main_selected_weapon = weapon
	weapon_icon.texture = weapon.item_icon


func _on_continue_button_pressed() -> void:
	SoundManager.player_sound(SoundManager.Sound.UI)
	if not Global.main_selected_player or not Global.main_selected_weapon:
		return
	on_selection_completed.emit()
	hide()
